package main;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.InterruptableJob;
import org.quartz.UnableToInterruptJobException;

import lib.WebsiteRunnable;

import pojo.Website;

import dao.WebsiteDAO;

@DisallowConcurrentExecution
public class ThreadPoolJob implements Job,  InterruptableJob {
	//private static boolean isJobRunning1 = false;
	//private static boolean isJobRunning2 = false;
	private ExecutorService executor = null;
	private List<Future<Object>> handlings = null;
	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
	
		executor = Executors.newFixedThreadPool(3);
		List<Callable<Object>> tasks = new ArrayList<Callable<Object>>();
		
		WebsiteDAO websitedao = new WebsiteDAO();
		List<Website> websites = websitedao.getList();
		for(int i = 0; i < websites.size(); i++){
			if(websites.get(i).getActive().compareTo("true") == 0){
				tasks.add(Executors.callable(new WebsiteRunnable(websites.get(i))));
			}
		}
		
		try {
			handlings = executor.invokeAll(tasks);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		executor.shutdown();
		//System.out.println("jobb da dung1");
		//System.out.println("jobb da dung1");
		SyncData sd = new SyncData();
		sd.sync();
		//try {
		//	sd.sync();
		//} catch (NamingException | SQLException e) {
			// TODO Auto-generated catch block
		//	e.printStackTrace();
		//}
	}
	
	//public static synchronized boolean getIsJobRunning1(){
	//	return isJobRunning1;
	//}
	//public static synchronized boolean getIsJobRunning2(){
	//	return isJobRunning2;
	//}
	
	@Override
	public void interrupt() throws UnableToInterruptJobException {
		// TODO Auto-generated method stub
		//System.out.println("jobb da dung2");

		System.out.println("jobb da dung2");
	}
}
